<template>
  <div id="cesiumContainer" class="cesium-map"></div>
  <!-- 水库调度详情dialog -->
  <el-dialog
    v-model="showReservoirInfoDialog"
    title="水库调度详情"
    width="1400px"
    :modal="false"
    draggable
    class="reservoir-info-dialog"
  >
    <div class="formItem">
      <p class="formItem__label">预报方案：</p>
      <el-select v-model="curPlanId" placeholder="请选择" popper-class="deep-select" @change="onChangePlan">
        <el-option v-for="item in planList" :key="item.id" :value="item.id" :label="item.name">{{
          item.name
        }}</el-option>
      </el-select>
    </div>
    <div class="infoContent">
      <div class="infoContent__feature">
        <div class="infoTitle">
          <span>特征值</span>
          <div class="infoTitle__line">
            <img src="/bottom_icon.svg" alt="" />
            <p></p>
          </div>
        </div>
        <div class="featureList">
          <div class="featureList__item">
            <span class="featureList__item--label">实测降雨：</span>
            <span class="featureList__item--value">{{ featureInfo?.realtimeRainfall ?? '-' }}</span>
            <span class="featureList__item--unit">mm</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">预报降雨：</span>
            <span class="featureList__item--value">{{ featureInfo?.forecastRainfall ?? '-' }}</span>
            <span class="featureList__item--unit">mm</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">降雨总量：</span>
            <span class="featureList__item--value">{{ featureInfo?.sumRainfall ?? '-' }}</span>
            <span class="featureList__item--unit">mm</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">起调水位：</span>
            <span class="featureList__item--value">{{ featureInfo?.initialLevel ?? '-' }}</span>
            <span class="featureList__item--unit">m</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">最高水位：</span>
            <span class="featureList__item--value">{{ featureInfo?.maxLevel ?? '-' }}</span>
            <span class="featureList__item--unit">m</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">入库洪峰：</span>
            <span class="featureList__item--value">{{ featureInfo?.maxInflow ?? '-' }}</span>
            <span class="featureList__item--unit">m³/s</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">出库洪峰：</span>
            <span class="featureList__item--value">{{ featureInfo?.maxOutflow ?? '-' }}</span>
            <span class="featureList__item--unit">m³/s</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">入库总量：</span>
            <span class="featureList__item--value">{{ featureInfo?.sumInflowCapacity ?? '-' }}</span>
            <span class="featureList__item--unit">万m³</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">出库总量：</span>
            <span class="featureList__item--value">{{ featureInfo?.sumOutflowCapacity ?? '-' }}</span>
            <span class="featureList__item--unit">万m³</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">调蓄总量：</span>
            <span class="featureList__item--value">{{ featureInfo?.interceptedWater ?? '-' }}</span>
            <span class="featureList__item--unit">万m³</span>
          </div>
          <div class="featureList__item">
            <span class="featureList__item--label">削峰率：</span>
            <span class="featureList__item--value">{{ featureInfo?.clipRate ?? '-' }}</span>
            <span class="featureList__item--unit">%</span>
          </div>
        </div>
      </div>
      <div class="infoContent__graph">
        <div class="progressHeader">
          <div class="infoTitle">
            <span>水库调度综合过程图</span>
            <div class="infoTitle__line">
              <img src="/bottom_icon.svg" alt="" />
              <p></p>
            </div>
          </div>
          <div class="btnWrap">
            <div
              :class="{ blueBtn: true, leftBtn: true, active: curProgeressBtnType === '图形' }"
              @click="onClickProgressBtn('图形')"
            >
              图形
            </div>
            <div
              :class="{ blueBtn: true, rightBtn: true, active: curProgeressBtnType === '表格' }"
              @click="onClickProgressBtn('表格')"
            >
              表格
            </div>
          </div>
        </div>
        <div class="progressWrap">
          <div v-show="curProgeressBtnType === '图形'" class="progressEcharts">
            <p class="wlText">水位（m）</p>
            <p class="rainText">雨量（mm）</p>
            <p class="flowText">流量（m³/s）</p>
            <div ref="echartsRef"></div>
          </div>
          <el-table
            v-show="curProgeressBtnType === '表格' && planInfo?.dataReservoirDispatchPlanList.length"
            class="cus-table2 pading-3"
            highlight-current-row
            :data="planInfo.dataReservoirDispatchPlanList"
            :cell-style="tabCellStyle"
            width="100%"
            max-height="550px"
            style="border: 1px solid rgba(8, 175, 255, 0.5); border-bottom: none"
          >
            <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
            <el-table-column label="时间" min-width="135" align="center" #default="{ row }">
              {{ row.dataTime ? row.dataTime.slice(0, 16) : '-' }}
            </el-table-column>
            <el-table-column label="降雨(mm)" #default="{ row }" min-width="80" align="center">{{
              getProperty(row.rainfall, '', false, 1, '-')
            }}</el-table-column>
            <el-table-column label="水位(m)" min-width="70" align="center" #default="{ row }">{{
              typeof row.level === 'number' ? row.level.toFixed(2) : '/'
            }}</el-table-column>
            <el-table-column label="入流(m³/s)" #default="{ row }" min-width="80" align="center">{{
              getProperty(row.inflow, '', false, 1, '-')
            }}</el-table-column>
            <el-table-column label="出流(m³/s)" #default="{ row }" min-width="80" align="center">{{
              getProperty(row.outflow, '', false, 1, '-')
            }}</el-table-column>
            <el-table-column label="库容(万m³)" #default="{ row }" min-width="80" align="center">{{
              getProperty(row.capacity, '', true, 1, '-')
            }}</el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { h, nextTick, onMounted, onUnmounted, ref } from 'vue';
import * as Cesium from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';
import { resApi } from '@/api/res';
import * as echarts from 'echarts';
import { getSkddEcOption, getProperty } from './echartsOptions.js';

// ✅ 使用您的天地图 TOKEN
const TIANDITU_TOKEN = '40ebdf578d4b77c8f3e64238cf2f2431';

let viewer = null;
let resInfo = {};
const reservoirCode = 'BGD1017633020320004';
const planList = ref([]);
const planInfo = ref();
const showReservoirInfoDialog = ref(false);
const curPlanId = ref();
const featureInfo = ref();
const echartsRef = ref();
const curProgeressBtnType = ref('图形'); // 图形 or 表格
let echartsInstance;

const onClickProgressBtn = (type) => {
  curProgeressBtnType.value = type;
  if (type === '图形') {
    setProgressEcharts(planInfo.value);
  }
};
const tabCellStyle = ({ columnIndex, row }) => {
  let color, fontWeight;
  if (columnIndex === 2) {
    fontWeight = 700;
    color = row.isHistory ? '#1892FA' : '#27D526';
    return { color, fontWeight };
  } else if (columnIndex === 3) {
    fontWeight = 700;
    color = '#20BCFF';
    return { color, fontWeight };
  } else if (columnIndex === 4) {
    color = '#9446FF';
    fontWeight = 700;
    return { color, fontWeight };
  } else if (columnIndex === 5) {
    color = '#B7FC54';
    fontWeight = 700;
    return { color, fontWeight };
  } else if (columnIndex === 6) {
    color = '#fff';
    fontWeight = 700;
    return { color, fontWeight };
  }
};
const onChangePlan = (id) => {
  resApi.getPlanInfoById({ id }).then((info) => {
    if (!info.dataReservoirDispatchPlanList.length) {
      planInfo.value.dataReservoirDispatchPlanList = [];
      featureInfo.value = {};
      echartsInstance && echartsInstance.dispose();
      return;
    }
    planInfo.value = info;
    featureInfo.value = info.featureReservoirDispatchPlan;
    showReservoirInfoDialog.value = true;
    setProgressEcharts(info);
  });
};
const setProgressEcharts = (info) => {
  const xData = [],
    inData = [],
    featureInData = [],
    outData = [],
    featureOutData = [],
    historyWl = [],
    featureWl = [],
    historyRain = [],
    featureRain = [];
  const nowIndex = info.dataReservoirDispatchPlanList.findIndex(
    (item) => item.dataTime === info.baseReservoirDispatchPlan.forecastTime,
  );
  // console.log(nowIndex); // 106
  info.dataReservoirDispatchPlanList.forEach((item, index) => {
    xData.push(item.dataTime);
    const isHistory = index <= nowIndex,
      isFeature = index >= nowIndex;
    item.isHistory = isHistory;
    inData.push(isHistory ? item.inflow : null);
    featureInData.push(isFeature ? item.inflow : null);
    outData.push(isHistory ? item.outflow : null);
    featureOutData.push(isFeature ? item.outflow : null);
    historyWl.push(isHistory ? item.level : null);
    featureWl.push(isFeature ? item.level : null);
    historyRain.push(isHistory ? item.rainfall : null);
    featureRain.push(!isHistory ? item.rainfall : null);
  });
  const skDDOption = getSkddEcOption(
    xData,
    inData,
    featureInData,
    outData,
    featureOutData,
    historyWl,
    featureWl,
    historyRain,
    featureRain,
    237.12,
    231.13,
    nowIndex,
  );
  nextTick(() => {
    echartsInstance && echartsInstance.dispose();
    echartsInstance = echarts.init(echartsRef.value);
    echartsInstance.setOption(skDDOption);
  });
};

onMounted(() => {
  // 初始化 Cesium Viewer
  viewer = new Cesium.Viewer('cesiumContainer', {
    // 禁用不必要的控件
    animation: false,
    timeline: false,
    baseLayerPicker: false,
    geocoder: false,
    homeButton: false,
    infoBox: false,
    navigationHelpButton: false,
    sceneModePicker: false,
    selectionIndicator: false,

    // 关键设置：禁用默认的Bing地图图层
    imageryProvider: false,
  });

  // 添加天地图影像图层（底图）
  const tdtImg = new Cesium.WebMapTileServiceImageryProvider({
    url: `https://t{s}.tianditu.gov.cn/img_w/wmts?tk=${TIANDITU_TOKEN}`,
    layer: 'img',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'w',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18,
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    credit: new Cesium.Credit('天地图影像'),
  });

  // 添加天地图中文注记图层
  const tdtCia = new Cesium.WebMapTileServiceImageryProvider({
    url: `https://t{s}.tianditu.gov.cn/cia_w/wmts?tk=${TIANDITU_TOKEN}`, // 注意这里是cia_w不是cia_c
    layer: 'cia',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'w',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18,
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    credit: new Cesium.Credit('天地图注记'),
  });

  // 添加图层到地球
  viewer.imageryLayers.addImageryProvider(tdtImg);
  viewer.imageryLayers.addImageryProvider(tdtCia);

  resApi.getResInfoByCode({ code: reservoirCode }).then((res) => {
    resInfo = res;
    // 设置初始视角：显示完整地球
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(resInfo.lon, resInfo.lat, 500000), // 从太空看地球
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-90), // 俯视地球
        roll: 0,
      },
      duration: 3,
    });

    const position = Cesium.Cartesian3.fromDegrees(resInfo.lon, resInfo.lat);
    const entity = viewer.entities.add({
      position: position,
      billboard: {
        image: '/da-shuiku.svg',
        width: 24,
        height: 24,
        scale: 1.0,
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        // scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 100000, 0.2)
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 550000),
      },
      label: {
        text: resInfo.name,
        font: '14pt sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, 28), // 文字位置偏移
        // scaleByDistance: new Cesium.NearFarScalar(500, 1.0, 20000, 0.5)
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 550000),
      },
    });

    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction((movement) => {
      const pickedObject = viewer.scene.pick(movement.position);
      if (Cesium.defined(pickedObject) && pickedObject.id === entity) {
        resApi.getPlanListByCode({ code: resInfo.code }).then((res) => {
          planList.value = res;
          curPlanId.value = res[0].id;
          onChangePlan(curPlanId.value);
        });
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  });
});

// 组件卸载时销毁Cesium实例
onUnmounted(() => {
  if (viewer && !viewer.isDestroyed) {
    viewer.destroy();
  }
});
</script>

<style scoped lang="scss">
p {
  margin: 0;
}
.cesium-map {
  width: 100%;
  height: 100vh; /* 确保全屏显示 */
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.infoTitle {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  span {
    margin-bottom: 4px;
    font-size: 18px;
    font-weight: bold;
    color: #07afff;
  }
  &__line {
    display: flex;
    align-items: center;
    width: 100%;
    img {
      height: 4px;
    }
    p {
      flex: 1;
      margin: 0;
      height: 1px;
      background: linear-gradient(14deg, #57b7ff, rgba(45, 122, 255, 0));
    }
  }
}
.formItem {
  display: flex;
  align-items: center;
  width: 300px;
  &__label {
    color: #07afff;
    white-space: nowrap;
  }
  :deep(.el-select__wrapper) {
    background: rgba(5, 101, 191, 0.2);
    box-shadow: inset 0 0 5px 1px rgba(0, 219, 255, 0.5);
    .el-select__placeholder {
      color: #fff;
    }
  }
}
.infoContent {
  display: flex;
  margin-top: 10px;
  &__feature {
    width: 200px;
    margin-right: 20px;
    .featureList {
      &__item {
        height: 40px;
        line-height: 40px;
        margin-top: 8px;
        background: url('/icon_static_bg.svg') no-repeat 50% / 100% auto;
        &--label {
          color: #07afff;
        }
        &--value {
          margin-right: 5px;
          color: #fff;
          font-weight: bold;
        }
        &--unit {
          color: #fff;
          font-size: 14px;
        }
      }
    }
  }
  &__graph {
    flex: 1;
  }
}
.progressHeader {
  display: flex;
  .infoTitle {
    flex: 1;
  }
}
.progressWrap {
  height: 550px;
  .progressEcharts {
    position: relative;
    width: 100%;
    height: 550px;
    div {
      width: 100%;
      height: 100%;
    }
    .wlText {
      position: absolute;
      top: 50%;
      left: -30px;
      transform: translateY(50%);
      color: #98c1ff;
      transform: scaleX(-1) scaleY(-1) rotate(90deg);
    }
    .rainText {
      position: absolute;
      right: -40px;
      top: 100px;
      color: #fec87b;
      transform: rotate(90deg);
    }
    .flowText {
      position: absolute;
      right: -40px;
      bottom: 100px;
      color: #98c1ff;
      transform: rotate(90deg);
    }
  }
}
.btnWrap {
  display: flex;
  .blueBtn {
    width: 64px;
    height: 24px;
    line-height: 24px;
    font-size: 14px;
    text-align: center;
    color: #fff;
    cursor: pointer;
    background: linear-gradient(
      180deg,
      rgba(10, 157, 224, 0.35),
      rgba(10, 153, 221, 0.35) 10%,
      rgba(10, 147, 218, 0.35) 20%,
      rgba(10, 139, 214, 0.35) 30%,
      rgba(8, 135, 211, 0.35) 40%,
      rgba(8, 130, 208, 0.35) 50%,
      rgba(7, 124, 204, 0.35) 60%,
      rgba(6, 118, 201, 0.35) 70%,
      rgba(6, 112, 198, 0.35) 80%,
      rgba(5, 107, 194, 0.35) 90%,
      rgba(5, 101, 191, 0.35)
    );
    &:hover {
      opacity: 0.85;
    }
    &.active {
      background: linear-gradient(
        1turn,
        rgba(11, 158, 225, 0.85),
        rgba(10, 153, 221, 0.85) 10%,
        rgba(10, 147, 218, 0.85) 20%,
        rgba(9, 141, 215, 0.85) 30%,
        rgba(8, 137, 212, 0.85) 40%,
        rgba(8, 130, 208, 0.85) 50%,
        rgba(7, 124, 204, 0.85) 60%,
        rgba(6, 118, 201, 0.85) 70%,
        rgba(6, 112, 198, 0.85) 80%,
        rgba(5, 107, 194, 0.85) 90%,
        rgba(5, 101, 191, 0.85)
      );
    }
  }
  .leftBtn {
    border-radius: 10px 0 0 10px;
    margin-right: 8px;
  }
  .rightBtn {
    border-radius: 0 10px 10px 0;
  }
}
:deep(.el-table) {
  &.pading-3 .cell {
    padding: vw(0 3) !important;
  }
  &.cus-table2 {
    color: #fff;
    background-color: transparent;
    border-color: rgba(8, 175, 255, 0.5);
    font-size: vw(14);

    ::-webkit-scrollbar {
      height: vw(12) !important;
    }

    &::after,
    &::before {
      z-index: 11;
      background-color: rgba(8, 175, 255, 0.5);
    }

    tr {
      background-color: transparent;
    }

    th,
    td {
      background-color: rgb(13, 13, 13) !important;
      border-color: rgba(8, 175, 255, 0.5) !important;
    }

    thead th {
      background: rgba(0, 0, 0, 0.8);
    }

    th {
      color: #40c4ff;

      &.is-leaf {
        border-color: transparent;
      }

      &.gutter {
        display: none;
        width: 0;
      }

      .cell {
        line-height: 1.1;
      }
    }

    colgroup col[name='gutter'] {
      display: none;
      width: 0;
    }

    .el-table__body {
      width: 100% !important;

      tr:hover > td {
        background-color: #1a5e9a !important;
      }

      tr.current-row > td {
        background-color: #59b6f8 !important;
      }
    }

    .el-table__empty-block {
      min-height: vw(40);

      .el-table__empty-text {
        line-height: vw(40);
        color: #fff;
      }
    }

    .el-table__fixed {
      tr th,
      tr td {
        background: rgb(13, 13, 13) !important;
      }

      &::before {
        background-color: rgba(8, 175, 255, 0);
      }
    }
  }
}
</style>
<style>
.reservoir-info-dialog {
  padding: 0 !important;
  border-top: 4px solid #07afff;
  border-bottom: 2px solid #07afff;
  background: rgba(15, 15, 15, 0.9) !important;
  .el-dialog__header {
    text-align: left;
    color: #07afff;
    background-image: linear-gradient(0deg, rgba(255, 255, 255, 0), rgba(7, 175, 255, 0.57));
    span {
      color: #07afff;
    }
  }
  .el-dialog__body {
    padding: 5px 20px;
  }
}
.deep-select {
  background: rgba(0, 43, 83, 0.8);
  box-shadow: inset 0 0 10px 2px #2a70a7;
  .el-select-dropdown__item {
    color: #fff;
  }
  .el-select-dropdown__item.is-hovering {
    background-color: inherit;
  }
}
</style>
